/**
 * Copyright (C), 2015-2018
 * FileName: DubboServicePlugin
 * Author:   Dayu Hou
 * Date:     2018/1/17 9:13
 * Description: 类似dubbo接口
 * History:
 * <author>          <time>         <desc>
 */
package com.apache.rpc.service.plugins;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.rpc.entity.RpcMonitoring;
import com.apache.rpc.service.monitoring.MonitoringDataBaseHelper;
import com.apache.tools.StrUtil;

import java.util.Map;

/**
 * RPC请求日志添加<br>
 *
 * @author Dayu Hou
 * @since 1.0.0
 */
public class SaveRpcReqLogPlugin implements PluginConnector {

    public Object execute(ParamsVo param) throws Exception {
        writeMonitoring(param);
        ResultEntity entity = getResultEntity("添加成功");
        return entity;
    }

    private ResultEntity getResultEntity(String message) {
        ResultEntity resultEntity = new ResultEntity();
        resultEntity.setResult("false");
        resultEntity.setMessage(message);
        return resultEntity;
    }

    public void writeMonitoring(ParamsVo param) {
        RpcMonitoring monitoring = new RpcMonitoring();
        monitoring.setBeanId(String.valueOf(param.getParams("beanId")));
        monitoring.setMethodKey(String.valueOf(param.getParams("methodKey")));
        param.delParamsByKey("beanId");
        param.delParamsByKey("methodKey");
        String requestsource = String.valueOf(param.getParams("requestSources"));
        param.delParamsByKey("requestSources");
        String startTime = String.valueOf(param.getParams("startTime"));
        String stopTime = String.valueOf(param.getParams("stopTime"));
        Map map = param.getParams();
        if (null != map || !map.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            if (StrUtil.isNotNull(String.valueOf(map.get("Client-IP")))) {
                sb.append(String.valueOf(map.get("Client-IP")) + "->");
            }
            if (StrUtil.isNotNull(String.valueOf(map.get("requestIp")))) {
                sb.append(String.valueOf(map.get("requestIp")) + "->");
            }
            sb.append(String.valueOf(map.get("rpcExeTimeAddr")));
            if (StrUtil.isNotNull(String.valueOf(map.get("rpcExeTimePort")))) {
                sb.append(":" + String.valueOf(map.get("rpcExeTimePort")));
            }
            monitoring.setServerAddr(sb.toString());
            map.remove("rpcExeTimeAddr");
            map.remove("Client-IP");
            map.remove("rpcExeTimePort");
            monitoring.setReqParams(map.toString());
        }
        monitoring.setMonitoring1(requestsource);//请求源
        monitoring.setStartTime(startTime);
        monitoring.setStopTime(stopTime);
        MonitoringDataBaseHelper.getInstance().exeMonitoring(monitoring);
    }

}